import { defineStore } from "pinia"
import { ref, computed } from 'vue'
import { insertCartAPI, getCartAPI, delCartAPI } from "@/apis/cart"
import { useUserStore } from "./user"

export const useCartStore = defineStore('cart', () => {
  const userStore = useUserStore()
  const isLogin = computed(() => userStore.userInfo.token)

  const cartList = ref([])
  const totalCount = computed(() => cartList.value.reduce((sum, item) => sum + item.count, 0))
  const totalPrice = computed(() => cartList.value.reduce((sum, item) => sum + item.count * item.price, 0))
  
  const updateCartList = async () => {
    const res = await getCartAPI()
    cartList.value = res.data.result
  }

  const delCart = async (skuId) => {
    if (isLogin.value) {
      await delCartAPI([skuId])
      updateCartList()
    } else {
      // 通过下标splice删除
      // 通过过滤filter删除
      const idx = cartList.value.findIndex(item => item.skuId === skuId)
      cartList.value.splice(idx, 1)
    }
  }
  const addCart = async (goods) => {
    const { skuId, count } = goods
    if (isLogin.value) {
      await insertCartAPI({ skuId, count })
      updateCartList()
    } else {
      const item = cartList.value.find(item => item.skuId === goods.skuId)
      if (item) {
        item.count++
      } else {
        cartList.value.push(goods)
      }
    }
  }

  const singleCheck = (skuId) => {
    const item = cartList.value.find((item) => item.skuId === skuId)
    item.selected = !item.selected
  }

  const allCheck = (selected) => {
    cartList.value.forEach((item) => item.selected = selected)
  }
  const isAll = computed(() => cartList.value.every((item) => item.selected))

  const selectedCount = computed(() => cartList.value.filter((item) => item.selected).reduce((sum, item) => sum + item.count, 0))
  const selectedPrice = computed(() => cartList.value.filter((item) => item.selected).reduce((sum, item) => sum + item.count * item.price, 0))

  const clearCart = () => {
    cartList.value = []
  }
  return {
    cartList,
    addCart,
    totalCount,
    delCart,
    totalPrice,
    singleCheck,
    allCheck,
    isAll,
    selectedCount,
    selectedPrice,
    clearCart,
    updateCartList
  }
},{
  persist: true
})